package view;

import model.Grade;
import model.Class;
import model.Subject;
import service.GradeService;
import service.ClassService;
import service.SubjectService;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.stream.Collectors;

public class GradeReportPanel extends JPanel {
    private JTable reportTable;
    private DefaultTableModel tableModel;
    private GradeService gradeService;
    private ClassService classService;
    private SubjectService subjectService;
    private JComboBox<ClassItem> classComboBox;
    private JComboBox<String> examTypeComboBox;
    private JComboBox<String> reportTypeComboBox;
    
    public GradeReportPanel() {
        gradeService = new GradeService();
        classService = new ClassService();
        subjectService = new SubjectService();
        initComponents();
        loadReportData();
    }
    
    private void initComponents() {
        setLayout(new BorderLayout());
        
        // 创建控制面板
        JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        
        // 班级选择
        controlPanel.add(new JLabel("班级："));
        classComboBox = new JComboBox<>();
        classComboBox.addItem(new ClassItem(0, "全部班级"));
        loadClassData();
        classComboBox.addActionListener(e -> loadReportData());
        controlPanel.add(classComboBox);
        
        // 考试类型选择
        controlPanel.add(new JLabel("考试类型："));
        examTypeComboBox = new JComboBox<>(
            new String[]{"全部", "期中考试", "期末考试", "单元测试", "模拟考试"}
        );
        examTypeComboBox.addActionListener(e -> loadReportData());
        controlPanel.add(examTypeComboBox);
        
        // 报表类型选择
        controlPanel.add(new JLabel("报表类型："));
        reportTypeComboBox = new JComboBox<>(
            new String[]{"成绩明细", "成绩汇总", "成绩排名"}
        );
        reportTypeComboBox.addActionListener(e -> loadReportData());
        controlPanel.add(reportTypeComboBox);
        
        add(controlPanel, BorderLayout.NORTH);
        
        // 创建表格
        tableModel = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        
        reportTable = new JTable(tableModel);
        reportTable.setAutoCreateRowSorter(true);
        
        JScrollPane scrollPane = new JScrollPane(reportTable);
        add(scrollPane, BorderLayout.CENTER);
    }
    
    // 用于ComboBox的班级项
    private static class ClassItem {
        private int id;
        private String name;
        
        public ClassItem(int id, String name) {
            this.id = id;
            this.name = name;
        }
        
        public int getId() { return id; }
        
        @Override
        public String toString() {
            return name;
        }
    }
    
    private void loadClassData() {
        List<model.Class> classes = classService.getAllClasses();
        for (model.Class cls : classes) {
            classComboBox.addItem(new ClassItem(cls.getId(), cls.getClassName()));
        }
    }
    
    private void loadReportData() {
        // 获取选中的班级和考试类型
        ClassItem selectedClass = (ClassItem) classComboBox.getSelectedItem();
        int classId = selectedClass != null ? selectedClass.getId() : 0;
        String examType = (String) examTypeComboBox.getSelectedItem();
        String reportType = (String) reportTypeComboBox.getSelectedItem();
        
        // 根据报表类型加载不同的数据
        switch (reportType) {
            case "成绩明细":
                loadDetailReport(classId, examType);
                break;
            case "成绩汇总":
                loadSummaryReport(classId, examType);
                break;
            case "成绩排名":
                loadRankingReport(classId, examType);
                break;
        }
    }
    
    private void loadDetailReport(int classId, String examType) {
        // 设置表头
        String[] columnNames = {"学号", "姓名", "班级", "科目", "成绩", "考试类型", "考试日期"};
        tableModel.setColumnIdentifiers(columnNames);
        tableModel.setRowCount(0);
        
        // 获取成绩数据
        List<Grade> grades;
        if (classId > 0) {
            grades = gradeService.getGradesByClass(classId);
        } else {
            grades = gradeService.getAllGrades();
        }
        
        // 过滤考试类型
        if (!"全部".equals(examType)) {
            grades = grades.stream()
                .filter(g -> examType.equals(g.getExamType()))
                .collect(Collectors.toList());
        }
        
        // 添加到表格
        for (Grade grade : grades) {
            Object[] rowData = {
                grade.getStudentNo(),
                grade.getStudentName(),
                grade.getClassName(),
                grade.getSubjectName(),
                grade.getScore(),
                grade.getExamType(),
                grade.getExamDate()
            };
            tableModel.addRow(rowData);
        }
    }
    
    private void loadSummaryReport(int classId, String examType) {
        // 设置表头
        String[] columnNames = {"科目", "参考人数", "最高分", "最低分", "平均分", "及格率"};
        tableModel.setColumnIdentifiers(columnNames);
        tableModel.setRowCount(0);
        
        // 获取统计数据
        Map<String, Object> stats = gradeService.getGradeStatistics(classId, null, examType);
        DecimalFormat df = new DecimalFormat("0.00");
        
        // 添加到表格
        stats.forEach((subject, statObj) -> {
            @SuppressWarnings("unchecked")
            Map<String, Object> stat = (Map<String, Object>) statObj;
            Object[] rowData = {
                subject,
                stat.get("total"),
                df.format(((Number) stat.get("highest")).doubleValue()),
                df.format(((Number) stat.get("lowest")).doubleValue()),
                df.format(((Number) stat.get("average")).doubleValue()),
                df.format(((Number) stat.get("passed")).doubleValue() * 100.0 / 
                         ((Number) stat.get("total")).doubleValue()) + "%"
            };
            tableModel.addRow(rowData);
        });
    }
    
    private void loadRankingReport(int classId, String examType) {
        // 设置表头
        String[] columnNames = {"排名", "学号", "姓名", "班级", "总分", "平均分"};
        tableModel.setColumnIdentifiers(columnNames);
        tableModel.setRowCount(0);
        
        // 获取成绩数据
        List<Grade> grades;
        if (classId > 0) {
            grades = gradeService.getGradesByClass(classId);
        } else {
            grades = gradeService.getAllGrades();
        }
        
        // 过滤考试类型
        if (!"全部".equals(examType)) {
            grades = grades.stream()
                .filter(g -> examType.equals(g.getExamType()))
                .collect(Collectors.toList());
        }
        
        // 计算每个学生的总分和平均分
        Map<String, StudentScore> scoreMap = new HashMap<>();
        for (Grade grade : grades) {
            String key = grade.getStudentNo() + "|" + grade.getStudentName() + "|" + grade.getClassName();
            scoreMap.computeIfAbsent(key, k -> new StudentScore()).addScore(grade.getScore());
        }
        
        // 转换为列表并排序
        List<Map.Entry<String, StudentScore>> rankList = new ArrayList<>(scoreMap.entrySet());
        rankList.sort((a, b) -> Double.compare(b.getValue().getTotal(), a.getValue().getTotal()));
        
        // 添加到表格
        DecimalFormat df = new DecimalFormat("0.00");
        int rank = 1;
        for (Map.Entry<String, StudentScore> entry : rankList) {
            String[] studentInfo = entry.getKey().split("\\|");
            StudentScore score = entry.getValue();
            
            Object[] rowData = {
                rank++,
                studentInfo[0],  // 学号
                studentInfo[1],  // 姓名
                studentInfo[2],  // 班级
                df.format(score.getTotal()),
                df.format(score.getAverage())
            };
            tableModel.addRow(rowData);
        }
    }
    
    // 用于计算学生总分和平均分的辅助类
    private static class StudentScore {
        private double total = 0;
        private int count = 0;
        
        public void addScore(double score) {
            total += score;
            count++;
        }
        
        public double getTotal() {
            return total;
        }
        
        public double getAverage() {
            return count > 0 ? total / count : 0;
        }
    }
} 